#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <time.h>

#include "ClientUapProxy.h"
#include "MgwGapProxy.h"
#include "ServicePool.h"
#include "Server.h"
#include "MessageQueue.h"
#include "Trace.h"

using namespace boost::asio;
using namespace tsc::common;
using namespace tsc::sgw;


/*******************************************************************************
 *
 * forward declaration
 *
 ******************************************************************************/
void mainProcLoop();
GeneratorEnvironment* pGe;
/*******************************************************************************
 *
 *
 *
 ******************************************************************************/
int main(int argc, char* argv[])
{
  ENABLE_ALL_TRACE();
  TRACE_PROCESS("S-GW");

  ENTER("main");
  try
  {
    if (argc != 3)
    {
      TRACE_ERROR("Usage: %s <address> <port>\n    %s 127.0.0.1 3333",
                argv[0], argv[0]);
      RETURN(1);
    }

    ServicePool pool;

    // init server side
    io_service& serverService = pool.getService();
    Server server(argv[1], argv[2], serverService);

    // init aplication side to client
    RequestHandler appHandler;
    MessageQueue::instance()->registerApplicationHandler(&appHandler);
    pGe = new GeneratorEnvironment;
    ClientUapProxy::init(&appHandler, *pGe);

    boost::thread* pThread = 0;
    pThread = new boost::thread(boost::bind(&mainProcLoop));
    pool.addTread(pThread);

    INFO("Server application starting.");
    pool.run();
  }
  catch (std::exception& exc)
  {
    TRACE_ERROR("Server application cought exception: %s", exc.what());
  }

  INFO("Server flushing messege queue.");
  MessageQueue::instance()->~MessageQueue();
  INFO("Server application finished.");
  RETURN(0);
}

/*******************************************************************************
 *
 *
 *
 ******************************************************************************/
void mainProcLoop()
{
  while (1)
  {
    Message* pMessage = 0;

    if (MessageQueue::instance()->fromInQueue(pMessage))
    {
      ClientUapProxy::instance().handlePdu(pMessage);
      if (pMessage)
      {
        TRACE_ERROR("Duudeee!");
        DELETE_MESSAGE_P(pMessage);
      }
    }
    pGe->deleteRemovedGenerators();
    sleep(1); // XXX WTF 1 second !!!!
  } // while(1)
}
